<?php

namespace app\admin\controller\depot;

use app\common\controller\Backend;


/**
 * vue商城
 *退货管理
 * @icon fa fa-user
 */
class Back extends Backend
{
    protected $relationSearch = true;
    protected $backPromodel = null;
    protected $ordermodel = null;
    protected $orderPromodel = null;
    protected $addressmodel = null;
    protected $businessmodel = null;
    protected $Storagemodel = null;
    protected $StorageProModel = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Depot.Back');
        $this->backPromodel = model('Depot.Back.Product');
        $this->ordermodel = model('Product.Order.Order');
        $this->orderPromodel = model('Product.Order.Product');
        $this->addressmodel = model('Business.Address');
        $this->businessmodel = model('Business.Business');
        $this->Storagemodel = model('Depot.Storage');
        $this->StorageProModel = model('Depot.Storage.Product');
        $status = [
            '0' => '未审核',
            '1' => '已审核，未收货',
            '2' => '已收货，未入库',
            '3' => '已入库',
            '-1' => '审核不通过',
        ];
        $this->view->assign('status', $status);
    }
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('business')
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with('business')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $ordercode = isset($params['ordercode']) ? $params['ordercode'] : 0;
            $addrid = isset($params['addrid']) ? $params['addrid'] : 0;
            $remark = isset($params['remark']) ? $params['remark'] : '';

            $orderinfo = $this->ordermodel->where('code', $ordercode)->find();

            if (!$orderinfo) {
                $this->error(__('订单不存在'));
            }
            $addressinfo = $this->addressmodel->find($addrid);

            if (!$addressinfo) {
                $this->error(__('收货地址不存在'));
            }
            $orderproductlist = $this->orderPromodel->where('orderid', $orderinfo['id'])->select();

            if (!$orderproductlist) {
                $this->error('订单商品不存在');
            }
            // 开启事务
            $this->model->startTrans();
            $this->backPromodel->startTrans();
            $BackData = [
                'ordercode' => $orderinfo['code'],
                'code' => build_code('BP'),
                'busid' => $orderinfo['busid'],
                'contact' => $addressinfo['consignee'],
                'phone' => $addressinfo['mobile'],
                'address' => $addressinfo['address'],
                'province' => $addressinfo['province'],
                'city' => $addressinfo['city'],
                'district' => $addressinfo['district'],
                'amount' => $orderinfo['amount'],
                'status'=>'0',
                'adminid'=>$this->auth->id,
                'remark' => $remark
            ];
            $BackStatus = $this->model->validate('common/Depot/back/Back')->save($BackData);
            if (!$BackStatus) {
                $this->error($this->model->getError());
            }
            $back = $this->model->where('code', $BackData['code'])->find();
            $BackProData = [];
            foreach ($orderproductlist as $item) {
                $BackProData[] = [
                    'backid' => $back['id'],
                    'proid' => $item['proid'],
                    'nums' => $item['pronum'],
                    'price' => $item['price'],
                    'total' => $item['total']
                ];
            }
            $BackProStatus = $this->backPromodel->validate('common/Depot/back/BackProduct')->saveAll($BackProData);
            if (!$BackProStatus) {
                $this->model->rollBack();
                $this->error($this->backPromodel->getError());
            }
            $this->model->commit();
            $this->backPromodel->commit();
            $this->success(__('退货订单添加成功'));
        }
        return $this->view->fetch();
    }
    // 详情
    public function detail($ids = null)
    {
        $row = $this->model->with(['business', 'districts', 'citys', 'provinces', 'expressquery', 'stroman', 'sale', 'review'])->find($ids);
        $BackProductData = $this->backPromodel->with(['products'])->where('backid', $ids)->select();
        $this->assign(['row' => $row, 'BackProductData' => $BackProductData]);
        return $this->view->fetch();
    }
    // 通过审核
    public function process($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('没有退货订单'));
        }
        $result = $this->model->isUpdate()->save(['id' => $row['id'], 'status' => "1", 'reviewerid' => $this->auth->id]);
        if ($result === false) {
            $this->error(__('操作失败'));
        }
        $this->success("操作成功");
    }
    // 不通过审核
    public function fail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('没有退货订单'));
        }
        $result = $this->model->isUpdate()->save(['id' => $row['id'], 'status' => "-1", 'reviewerid' => $this->auth->id]);
        if ($result === false) {
            $this->error(__('操作失败'));
        }
        $this->success("操作成功");
    }
    // 撤销审核
    public function cancel($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('没有退货订单'));
        }
        $result = $this->model->isUpdate()->save(['id' => $row['id'], 'status' => '0', 'reviewerid' => null]);
        if ($result === false) {
            $this->error(__('操作失败'));
        }
        $this->success("操作成功");
    }
    // 编辑
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $ordercode = isset($params['ordercode']) ? $params['ordercode'] : 0;
            $addrid = isset($params['addrid']) ? $params['addrid'] : 0;
            $remark = isset($params['remark']) ? $params['remark'] : '';
            $backinfo = $this->model->where('ordercode', $ordercode)->find();
            if (!$backinfo) {
                $this->error(__('退货订单不存在'));
            }
            $addressinfo = $this->addressmodel->find($addrid);

            if (!$addressinfo) {
                $this->error(__('收货地址不存在'));
            }
            $BackData = [
                "id" => $backinfo['id'],
                'ordercode' => $ordercode,
                'contact' => $addressinfo['consignee'],
                'phone' => $addressinfo['mobile'],
                'address' => $addressinfo['address'],
                'province' => $addressinfo['province'],
                'city' => $addressinfo['city'],
                'district' => $addressinfo['district'],
                'remark' => $remark
            ];
            $result = $this->model->validate('common/Depot/back/Back.edit')->isUpdate()->save($BackData);
            if ($result === false) {
                $this->error($this->model->getError());
            }
            $this->success('编辑成功');
        }
        $row = $this->model->find($ids);
        $order = $this->ordermodel->where('code', $row['ordercode'])->find();;
        $AddressList = $this->addressmodel->with(['districts', 'citys', 'provinces'])->where('busid', $order['busid'])->select();
        $row['addrid'] = 0;
        $addressList = [];
        foreach ($AddressList as $item) {
            $addressList[$item['id']] = "联系人：" . $item['consignee'] . " 联系方式：" . $item['mobile'] . "地址：" . $item['provinces']['name'] . "-" . $item['citys']['name'] . "-" . $item['districts']['name'] . $item['address'];
            if ($item['district'] == $order['district'] && $item['city'] == $order['city'] && $item['provinces'] == $order['province'] && $item['consignee'] == $order['consignee'] && $item['mobile'] == $order['mobile'] && $item['address'] == $order['address']) {
                $row['addrid'] = $item['id'];
            }
        }
        $BackProductList = $this->backPromodel->with('products')->where('backid', $row['id'])->select();
        $this->assignconfig('BackProductList', $BackProductList);
        $this->view->assign(['row' => $row, 'AddressList' => $addressList]);
        return $this->view->fetch();
    }
    // 获取订单
    public function order()
    {
        $code = $this->request->param('code', 0, 'trim');

        $order = $this->ordermodel->where('code', $code)->find();

        $res = ['code' => 0, 'msg' => '', 'data' => ''];
        if (!$order) {
            $res['msg'] = '没有该订单';
            return json($res);
        }
        $AddressList = $this->addressmodel->with(['districts', 'citys', 'provinces'])->where('busid', $order['busid'])->select();
        $order['businessaddrid'] = 0;

        foreach ($AddressList as $item) {

            if ($item['district'] == $order['district'] && $item['city'] == $order['city'] && $item['provinces'] == $order['province'] && $item['consignee'] == $order['consignee'] && $item['mobile'] == $order['mobile'] && $item['address'] == $order['address']) {
                $order['businessaddrid'] = $item['id'];
            }
        }
        $orderProduct = $this->orderPromodel->with('products')->where('orderid', $order['id'])->select();

        foreach ($orderProduct as $item) {
            $ProductData[] = [
                'id' => $item['products']['id'],
                'name' => $item['products']['name'],
                'pronum' => $item['pronum'],
                'price' => $item['price'],
                'total' => $item['total']
            ];
        }
        $res['code'] = 1;
        $data = ['order' => $order, 'OrderProduct' => $ProductData, 'AddressList' => $AddressList];
        $res['data'] = $data;
        return json($res);
    }
    // 确认收货
    public function receipt($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('没有退货订单'));
        }
        // 开启事务
        $this->model->startTrans();
        $this->businessmodel->startTrans();
        $this->ordermodel->startTrans();
        $result = $this->model->isUpdate()->save(['id' => $row['id'], 'status' => "2"]);
        if ($result === false) {
            $this->error(__('操作失败'));
        }
        $orderRes = $this->ordermodel->where('code', $row['ordercode'])->update(['status' => "-4"]);
        if ($orderRes === false) {
            $this->model->rollBack();
            $this->error(__('操作失败'));
        }
        $businessinfo = $this->businessmodel->find($row['busid']);
        if (!$businessinfo) {
            $this->error(__('没有用户信息'));
        }
        if ($row['amount'] <= 0) {
            $this->error(__('订单总价不能小于或者等于0'));
        }
        $money = bcadd($row['amount'], $businessinfo['money'], 2);
        $businessData = ['id' => $row['busid'], 'money' => $money];
        $busRes = $this->businessmodel->isUpdate()->save($businessData);
        if ($busRes === false) {
            $this->model->rollBack();
            $this->ordermodel->rollBack();
            $this->error(__('操作失败'));
        }
        $this->model->commit();
        $this->businessmodel->commit();
        $this->ordermodel->commit();
        $this->success("操作成功");
    }
    // 入库
    public function storage($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('没有退货订单'));
        }
        // 开启事务
        $this->model->startTrans();
        $this->Storagemodel->startTrans();
        $this->StorageProModel->startTrans();

        // 封装入库数据
        $StorageData = [
            'code' => build_code('SU'),
            'type' => '2',
            'amount' => $row['amount'],
            'status' => 0
        ];

        $StorageStatus = $this->Storagemodel->validate('common/Depot/storage/Storage.back')->save($StorageData);
        if ($StorageStatus === FALSE) {
            $this->error($this->model->getError());
        }
        $productList = $this->backPromodel->with('products')->where('backid', $row['id'])->select();
        // 存放封装好的商品数据
        $ProductData = [];

        foreach ($productList as $item) {
            $ProductData[] = [
                'storageid' => $this->Storagemodel->id,
                'proid' => $item['id'],
                'nums' => $item['nums'],
                'price' => $item['price'],
                'total' => $item['total'],
            ];
        }

        // 验证数据
        $ProductStatus = $this->StorageProModel->validate('common/Depot/storage/Product')->saveAll($ProductData);

        if ($ProductStatus === FALSE) {
            $this->Storagemodel->rollback();
            $this->error($this->StorageProModel->getError());
        }
        $result = $this->model->isUpdate()->save(['id' => $row['id'], 'status' => "3", 'storageid' => $this->Storagemodel->id, 'stromanid' => $this->auth->id]);
        if ($result === false) {
            $this->Storagemodel->rollback();
            $this->StorageProModel->rollback();
            $this->error(__('操作失败'));
        }
        $this->model->commit();
        $this->Storagemodel->commit();
        $this->StorageProModel->commit();
        $this->success("操作成功");
    }
    // 软删除
    public function del($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('退货数据不存在'));
        }
        $result = $this->model->destroy($ids);
        if ($result === false) {
            $this->error("操作失败");
        }
        $this->success("操作成功");
    }
    /**
     * 退货回收站首页
     */
    public function recyclebin()
    {

        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->onlyTrashed()
                ->with('business')
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->onlyTrashed()
                ->with('business')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
    }
      /**
     * 退货回收站还原
     */
    public function restore($ids=null){
        $row = $this->model->onlyTrashed()->select($ids);
        if (empty($row)) {
            $this->error('当前退货数据不存在');
        }
        $res=$this->model->onlyTrashed()->where('id','IN',$ids)->update(['deletetime'=>null]);
         if($res==0){
                $this->error($this->model->getError());
        }
       $this->success();
    }
    /**
     * 退货回收站删除
     */
    public function destroy($ids=null){
        $res=$this->model->destroy($ids,true);
         if($res==0){
                $this->error($this->model->getError());
        }
       $this->success('删除成功');
    }
}
